<?php

/**
 * Kao Controller
 * 
 * Kao: PHP Web Framework <http://kao.byhuy.com/>.
 * Copyright 2008, Huy Nguyen <http://www.byhuy.com/>.
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

abstract class Kao_Controller
{
    /**
     * Request object
     */
    protected $_request = null;
    
    /**
     * Response object
     */
    protected $_response = null;
    
    /**
     * View object
     */
    protected $_view = null;
    
    /**
     * Loader object
     */
    protected $_loader = null;
    
    /**
     * Name of the handler function.
     */
    protected $_handler = null;
    
    /**
     * Constructor
     * 
     * @param Kao_Request $request
     */
    public function __construct(Kao_Request $request)
    {
        $this->_request = $request;
        
        $this->_handler = '__handle' . ucfirst(strtolower($request->getHttpMethod()));
        
        $this->_response = new Kao_Response();
    }
    
    
    /**
     * Override the handler name.
     * 
     * @param string $handlerName - Handler mame
     * @return Kao_Controller
     */
    public function setHandler($handlerName)
    {
        $this->_handler = $handlerName;
        return $this;
    }
    
    /**
     * Get request object
     */
    public function getRequest()
    {
        return $this->_request;
    }
    
    /**
     * Get response object
     */
    public function getResponse()
    {
        return $this->_response;
    }
    
    /**
     * HTTP GET handler
     */
    public function __handleGet()
    {
        // Not implemented
        $this->_response->setResponseCode(501);
    }
    
    /**
     * HTTP POST handler
     */
    public function __handlePost()
    {
        // Not implemented
        $this->_response->setResponseCode(501);
    }
    
    /**
     * HTTP PUT handler
     */
    public function __handlePut()
    {
        // Not implemented
        $this->_response->setResponseCode(501);
    }
    
    /**
     * HTTP DELETE handler
     */
    public function __handleDelete()
    {
        // Not implemented
        $this->_response->setResponseCode(501);
    }
    
    /**
     * HTTP HEAD handler
     */
    public function __handleHead()
    {
        // Not implemented
        $this->_response->setResponseCode(501);
    }
    
    /**
     * Dispatch function
     */
    public function serve()
    {
        if (!method_exists($this, $this->_handler))
        {
            $this->_response->setResponseCode(500);
            // TODO do something else here
            
        }
        else
        {
            $this->{$this->_handler}();
        }
        return $this->_response;
    }
}

